//
//  CYLPlusButtonSubclass.m
//  SleepNews
//
//  Created by Kavee DJ on 2017/1/11.
//  Copyright © 2017年 Kavee DJ. All rights reserved.
//

#import "CYLPlusButtonSubclass.h"
#import "RZPopupMenuView.h"
#import "SNKWeatherViewController.h"

#import "LCCKUtil.h"
#import <LCChatKit.h>
#import "LCChatKitExample.h"
#import "LCCKUser.h"
#import "LCCKContactManager.h"

#import "XFLoginViewController.h"

#import <FTPopOverMenu.h>

@interface CYLPlusButtonSubclass ()<RZPopupMenuViewDelegate>

@property (nonatomic, strong) RZPopupMenuView *popupMenu;

@property (nonatomic, readwrite, strong) CYLTabBarController *tabBarController;
@property (nonatomic, strong) LCCKConversationListViewController *firstViewController;
@property (nonatomic, strong) LCCKContactListViewController *secondViewController;

@end

@implementation CYLPlusButtonSubclass

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.adjustsImageWhenHighlighted = NO;
        
    }
    return self;
}

//上下结构的 button
- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 控件大小,间距大小
    // 注意：一定要根据项目中的图片去调整下面的0.7和0.9，Demo之所以这么设置，因为demo中的 plusButton 的 icon 不是正方形。
    CGFloat const imageViewEdgeWidth   = self.bounds.size.width * 0.4;
    CGFloat const imageViewEdgeHeight  = imageViewEdgeWidth * 1;
    
    CGFloat const centerOfView    = self.bounds.size.width * 0.5;
    CGFloat const labelLineHeight = self.titleLabel.font.lineHeight;
    CGFloat const verticalMargin  = (self.bounds.size.height - labelLineHeight - imageViewEdgeHeight) * 0.5;
    
    // imageView 和 titleLabel 中心的 Y 值
    CGFloat const centerOfImageView  = verticalMargin + imageViewEdgeHeight * 0.5 + 6.6;
    CGFloat const centerOfTitleLabel = imageViewEdgeHeight  + verticalMargin * 2 + labelLineHeight * 0.5 + 10;
    
    //imageView position 位置
    self.imageView.bounds = CGRectMake(0, 0, imageViewEdgeWidth, imageViewEdgeHeight);
    self.imageView.center = CGPointMake(centerOfView, centerOfImageView);
    
    //title position 位置
    self.titleLabel.bounds = CGRectMake(0, 0, self.bounds.size.width, labelLineHeight);
    self.titleLabel.center = CGPointMake(centerOfView, centerOfTitleLabel);
}

// 中间的Button
+ (id)plusButton {
    CYLPlusButtonSubclass *button = [[CYLPlusButtonSubclass alloc] init];
    [button setImage:[UIImage imageNamed:@"icon-plus"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"bg-addbutton"] forState:UIControlStateNormal];
    [button setTitle:@"发布" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
//    [button setTitle:@"选中" forState:UIControlStateSelected];
//    [button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    
    button.titleLabel.font = [UIFont systemFontOfSize:11];
    
    button.frame = CGRectMake(0.0, 0.0, 50, 50);
//    button.backgroundColor = [UIColor redColor];
    
    [button addTarget:button action:@selector(clickPublish) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

#pragma mark -
#pragma mark - Event Response

- (void)clickPublish {
    [self openBtnClick];
}

+ (CGFloat)multiplierOfTabBarHeight:(CGFloat)tabBarHeight {
    return  0.5;
}

+ (CGFloat)constantOfPlusButtonCenterYOffsetForTabBarHeight:(CGFloat)tabBarHeight {
    return -20;
}

#pragma mark - RZPopupMenuViewDelegate
- (void)popupMenuView:(RZPopupMenuView *)view selectedIndex:(NSInteger)index
{
    KLog(@"%ld", (long)index)
    
    
    IMP_BLOCK_SELF(CYLPlusButtonSubclass)
    
    if (index == 0) { // 暂时用第一个按钮,作为演示
        
        BOOL isLogin = nil;
        if ([AVUser currentUser].objectId != nil) { // 登录了
            
            isLogin = YES;
            [LCCKUtil showProgressText:@"open client ..." duration:10.0f];
            [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:[AVUser currentUser].objectId success:^{
                [LCCKUtil hideProgress];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:block_self.viewControllers.firstObject animated:YES completion:nil];
                
            } failed:^(NSError *error) {
                [LCCKUtil hideProgress];
                KLog(@"%@",error)
            }];
            
        }else {
            isLogin = NO;
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:[[XFLoginViewController alloc] init] animated:YES completion:nil];
        }
        
    } else if (index == 1) {
        
        BOOL isLogin = nil;
        if ([AVUser currentUser].objectId != nil) { // 登录了
            
            isLogin = YES;
            [LCCKUtil showProgressText:@"open client ..." duration:10.0f];
            [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:[AVUser currentUser].objectId success:^{
                [LCCKUtil hideProgress];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:block_self.viewControllers.lastObject animated:YES completion:nil];
                
            } failed:^(NSError *error) {
                [LCCKUtil hideProgress];
                KLog(@"%@",error)
            }];
            
        }else {
            isLogin = NO;
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:[[XFLoginViewController alloc] init] animated:YES completion:nil];
        }
        
        
        /******************************************
        // 设置用户体系,集成 LeanCloud 原生的用户系统 AVUser
        [[LCChatKit sharedInstance] setFetchProfilesBlock:^(NSArray<NSString *> *userIds, LCCKFetchProfilesCompletionHandler completionHandler) {
            NSMutableArray<id<LCCKUserDelegate>> *userList = [NSMutableArray array];
            for (NSString *userId in userIds) {
                //MyUser is a subclass of AVUser, conforming to the LCCKUserDelegate protocol.
                AVQuery *query = [[AVQuery alloc] init];
                NSError *error = nil;
                AVUser *user = (AVUser *)[query getObjectWithId:userId error:&error];
                LCCKUser *object = [LCCKUser userWithClientId:user.objectId];
                if (error == nil) {
                    [userList addObject:object];
                } else {
                    if (completionHandler) {
                        completionHandler(nil, error);
                        return;
                    }
                }
            }
            if (completionHandler) {
                completionHandler(userList, nil);
            }
        }
         ];
        
        
        
        BOOL isLogin = nil;
        if ([AVUser currentUser].objectId != nil) { // 登录了
            isLogin = YES;
        }else {
            isLogin = NO;
        }
        if (isLogin) { // 登录了才处理逻辑
            // 开启会话
            [[LCChatKit sharedInstance] openWithClientId:IS_IPHONE6?@"William":@"Tom" callback:^(BOOL succeeded, NSError *error) {
                LCCKConversationViewController *conversationViewController = [[LCCKConversationViewController alloc] initWithPeerId:IS_IPHONE6?@"Tom":@"William"];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:conversationViewController animated:YES completion:nil];
            }];
        } else {
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:[[XFLoginViewController alloc] init] animated:YES completion:nil];
        }
         ************************************************/
    } else if (index == 2) {
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:[[SNKWeatherViewController alloc] init] animated:YES completion:nil];
    }
}

#pragma mark - 消息,联系人

- (NSArray *)allPersonIds {
    NSArray *allPersonIds = [[LCCKContactManager defaultManager] fetchContactPeerIds];
    return allPersonIds;
}

- (NSArray *)viewControllers {
    LCCKConversationListViewController *firstViewController = [[LCCKConversationListViewController alloc] init];
    UINavigationController *firstNavigationController = [[LCCKBaseNavigationController alloc]
                                                         initWithRootViewController:firstViewController];
    [firstViewController configureBarButtonItemStyle:LCCKBarButtonItemStyleAdd action:^(__kindof LCCKBaseViewController *viewController, UIBarButtonItem *sender, UIEvent *event) {
        [self showPopOverMenu:sender event:event];
    }];
    firstViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出"
                                                                                              style:UIBarButtonItemStylePlain
                                                                                             target:self
                                                                                             action:@selector(dismiss)];
    
    self.firstViewController = firstViewController;
    NSArray *users = [[LCChatKit sharedInstance] getCachedProfilesIfExists:self.allPersonIds shouldSameCount:YES error:nil];
    NSString *currentClientID = [[LCChatKit sharedInstance] clientId];
    LCCKContactListViewController *secondViewController = [[LCCKContactListViewController alloc] initWithContacts:[NSSet setWithArray:users]  userIds:[NSSet setWithArray:self.allPersonIds] excludedUserIds:[NSSet setWithArray:@[currentClientID]] mode:LCCKContactListModeNormal];
    [secondViewController setSelectedContactCallback:^(UIViewController *viewController, NSString *peerId) {
//        [LCChatKitExample exampleOpenConversationViewControllerWithPeerId:peerId fromNavigationController:self.firstViewController.navigationController];
    }];
    [secondViewController setDeleteContactCallback:^BOOL(UIViewController *viewController, NSString *peerId) {
        [[LCCKContactManager defaultManager] removeContactForPeerId:peerId];
        return YES;
    }];
    self.secondViewController = secondViewController;
    UINavigationController *secondNavigationController = [[LCCKBaseNavigationController alloc]
                                                          initWithRootViewController:secondViewController];
    secondViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出"
                                                                                              style:UIBarButtonItemStylePlain
                                                                                             target:self
                                                                                             action:@selector(signOut)];
    secondViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加好友"
                                                                                             style:UIBarButtonItemStylePlain
                                                                                            target:self
                                                                                            action:@selector(addFriend)];
    NSArray *viewControllers = @[
                                 firstNavigationController,
                                 secondNavigationController,
                                 ];
    return viewControllers;
}

- (void)showPopOverMenu:(UIBarButtonItem *)sender event:(UIEvent *)event {
    [FTPopOverMenu showFromEvent:event
                        withMenu:@[ @"创建群聊" ]
                       doneBlock:^(NSInteger selectedIndex) {
                           if (selectedIndex == 0) {
                               [self createGroupConversation:sender];
                           }
                       } dismissBlock:nil];
}

- (void)createGroupConversation:(id)sender {
    [LCChatKitExample exampleCreateGroupConversationFromViewController:self.firstViewController];
}

- (void)signOut {
    [self.secondViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)dismiss {
    [self.firstViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)addFriend {
    
}


#pragma mark - event response
- (void)openBtnClick
{
    [RZPopupMenuView showWithDelegate:self];
}

@end
